<template>
  <div class="event-registration-container">
    <div class="event-header">
      <h1>社区活动报名</h1>
      <div class="event-stats">
        <div class="stat-card">
          <span class="stat-icon">📊</span>
          <div class="stat-content">
            <h3>已报名活动</h3>
            <p>{{ myRegistrations.length }}</p>
          </div>
        </div>
        <div class="stat-card">
          <span class="stat-icon">🎯</span>
          <div class="stat-content">
            <h3>进行中活动</h3>
            <p>{{ activeEvents.length }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 活动列表 -->
    <div class="events-section">
      <div class="events-filter">
        <button
            v-for="filter in filters"
            :key="filter.value"
            :class="['filter-btn', { active: currentFilter === filter.value }]"
            @click="currentFilter = filter.value"
        >
          {{ filter.label }}
        </button>
      </div>

      <div class="events-grid">
        <div
            v-for="event in filteredEvents"
            :key="event.eventId"
            class="event-card"
            @click="showEventDetail(event)"
        >
          <div class="event-image">
            <img
                :src="getEventImage(event) || 'https://via.placeholder.com/300x200?text=活动图片'"
                :alt="event.title"
            >
            <span class="event-status" :class="getEventStatus(event)">
              {{ getStatusText(getEventStatus(event)) }}
            </span>
          </div>
          <div class="event-content">
            <h3>{{ event.title }}</h3>
            <p class="event-desc">{{ event.description }}</p>
            <div class="event-details">
              <div class="detail-item">
                <span class="icon">📅</span>
                <span>活动日期：{{ formatDate(event.eventDate) }}</span>
              </div>
              <div class="detail-item">
                <span class="icon">🕒</span>
                <span>报名时间：{{ formatDate(event.registrationOpen) }} - {{ formatDate(event.registrationClose) }}</span>
              </div>
            </div>
            <div class="event-actions">
              <button
                  v-if="!isRegistered(event.eventId)"
                  @click="register(event)"
                  :disabled="getEventStatus(event) !== 'active'"
                  class="register-btn"
              >
                {{
                  getEventStatus(event) === 'upcoming' ? '未开始' :
                      getEventStatus(event) === 'closed' ? '已截止' :
                          getEventStatus(event) === 'completed' ? '已结束' : '立即报名'
                }}
              </button>
              <button
                  v-else
                  @click="cancelRegistration(event)"
                  class="cancel-btn"
              >
                取消报名
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 活动详情弹窗 -->
    <div v-if="selectedEvent" class="event-detail-modal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ selectedEvent.title }}</h2>
          <button class="close-btn" @click="selectedEvent = null">×</button>
        </div>

        <div class="modal-body">
          <div class="event-info">
            <img
                :src="getEventImage(selectedEvent)"
                :alt="selectedEvent.title"
                class="event-detail-image"
            >
            <p class="event-description">{{ selectedEvent.description }}</p>
            <div class="event-time-info">
              <p><span class="label">活动时间：</span>{{ formatDate(selectedEvent.eventDate) }}</p>
              <p><span class="label">报名时间：</span>{{ formatDate(selectedEvent.registrationOpen) }} -
                {{ formatDate(selectedEvent.registrationClose) }}</p>
            </div>
          </div>

          <div class="registrations-list">
            <h3>已报名人员 ({{ eventRegistrations.length }})</h3>
            <div class="registrations-grid">
              <div v-for="reg in eventRegistrations" :key="reg.registrationId" class="registration-item">
                <div class="user-avatar">{{ reg.ownerName?.[0] || '?' }}</div>
                <div class="registration-info">
                  <span class="user-name">{{ reg.ownerName || '未知用户' }}</span>
                  <span class="register-time">{{ formatRegisteredTime(reg.registeredAt) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 通知消息 -->
    <div v-if="error" class="notification error">{{ error }}</div>
    <div v-if="success" class="notification success">{{ success }}</div>
  </div>
</template>

<script>
export default {
  name: 'EventRegistration',
  data() {
    return {
      events: [],
      myRegistrations: [],
      currentFilter: 'all',
      error: null,
      success: null,
      filters: [
        {label: '全部活动', value: 'all'},
        {label: '我的报名', value: 'registered'},
        {label: '进行中', value: 'active'}
      ],
      selectedEvent: null,
      eventRegistrations: []
    }
  },
  computed: {
    activeEvents() {
      const now = new Date()
      return this.events.filter(event => {
        const regOpen = new Date(event.registrationOpen)
        const regClose = new Date(event.registrationClose)
        const eventDate = new Date(event.eventDate)

        // 活动在报名期间且未结束
        return now >= regOpen && now <= regClose && now <= eventDate
      })
    },
    filteredEvents() {
      let filteredResult = this.events

      switch (this.currentFilter) {
        case 'registered': {
          const registeredEventIds = this.myRegistrations
              .filter(reg => reg.event !== null)
              .map(reg => reg.event.eventId)
          filteredResult = this.events.filter(event =>
              registeredEventIds.includes(event.eventId)
          )
          break
        }
        case 'active':
          filteredResult = this.activeEvents
          break
      }

      return filteredResult
    }
  },
  methods: {
    async fetchEvents() {
      try {
        const response = await fetch('http://localhost:8080/api/events')
        if (!response.ok) throw new Error('获取活动列表失败')
        this.events = await response.json()
      } catch (err) {
        this.error = err.message
      }
    },

    async fetchMyRegistrations() {
      const user = JSON.parse(localStorage.getItem('user'))
      if (!user?.ownerId) return
      try {
        const response = await fetch(`http://localhost:8080/api/registrations/owner/${user.ownerId}`)
        if (!response.ok) throw new Error('获取报名记录失败')
        const registrations = await response.json()

        // 过滤掉无效记录并保存完整的活动信息
        this.myRegistrations = registrations.filter(reg =>
            reg.event !== null && reg.event_id !== null && reg.owner_id !== null
        )
      } catch (err) {
        this.error = err.message
      }
    },

    isRegistered(eventId) {
      return this.myRegistrations.some(reg =>
          reg.event && reg.event.eventId === eventId
      )
    },

    async register(event) {
      const user = JSON.parse(localStorage.getItem('user'))
      if (!user?.ownerId) {
        this.error = '请先登录'
        return
      }

      try {
        const response = await fetch('http://localhost:8080/api/registrations', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            event_id: event.eventId,
            owner_id: user.ownerId
          })
        })

        if (!response.ok) {
          const errorText = await response.text()
          throw new Error(errorText)
        }

        await this.fetchMyRegistrations()
        this.success = '报名成功！'
      } catch (err) {
        this.error = err.message
      }
    },

    async cancelRegistration(event) {
      const registration = this.myRegistrations.find(reg => reg.event_id === event.eventId)
      if (!registration) return

      try {
        const response = await fetch(`http://localhost:8080/api/registrations/${registration.registrationId}`, {
          method: 'DELETE'
        })

        if (!response.ok) throw new Error('取消报名失败')

        await this.fetchMyRegistrations()
        this.success = '已取消报名'
      } catch (err) {
        this.error = err.message
      }
    },

    getEventStatus(event) {
      const now = new Date()
      const regOpen = new Date(event.registrationOpen)
      const regClose = new Date(event.registrationClose)
      const eventDate = new Date(event.eventDate)

      if (now < regOpen) {
        return 'upcoming'  // 未开始报名
      } else if (now > eventDate) {
        return 'completed'  // 活动已结束
      } else if (now > regClose) {
        return 'closed'  // 报名已截止
      } else if (now >= regOpen && now <= regClose) {
        return 'active'  // 报名进行中
      }
    },

    getStatusText(status) {
      const statusMap = {
        'upcoming': '未开始报名',
        'active': '报名进行中',
        'closed': '报名已截止',
        'completed': '活动已结束'
      }
      return statusMap[status] || status
    },

    formatDate(dateString) {
      if (!dateString) return '待定'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    },

    formatRegisteredTime(dateString) {
      if (!dateString) return ''
      return new Date(dateString).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    getEventImage(event) {
      // 根据活动标题或描述判断活动类型，返回对应的图片URL
      const title = event.title.toLowerCase()
      const desc = event.description.toLowerCase()

      if (title.includes('烘焙') || desc.includes('烘焙')) {
        return 'https://img.freepik.com/free-photo/family-cooking-together-kitchen_23-2148883831.jpg'
      }

      if (title.includes('春节') || desc.includes('春节')) {
        return 'https://img.freepik.com/free-photo/chinese-new-year-concept-with-lantern_23-2148740034.jpg'
      }

      if (title.includes('摄影') || desc.includes('摄影')) {
        return 'https://img.freepik.com/free-photo/camera-photographic-with-smartphone-devices-generative-ai_188544-12171.jpg'
      }

      if (title.includes('健康') || desc.includes('健康')) {
        return 'https://img.freepik.com/free-photo/doctor-with-stethoscope-hands-hospital-background_1423-1.jpg'
      }

      // 默认图片
      return 'https://img.freepik.com/free-photo/group-diverse-people-having-business-meeting_53876-25060.jpg'
    },

    async showEventDetail(event) {
      this.selectedEvent = event
      await this.fetchEventRegistrations(event.eventId)
    },

    async fetchEventRegistrations(eventId) {
      try {
        // 获取报名记录
        const response = await fetch(`http://localhost:8080/api/registrations/event/${eventId}`)
        if (!response.ok) throw new Error('获取报名信息失败')
        const registrations = await response.json()

        // 获取所有业主信息
        const ownersResponse = await fetch('http://localhost:8080/api/owners')
        if (!ownersResponse.ok) throw new Error('获取业主信息失败')
        const owners = await ownersResponse.json()

        // 将业主信息添加到报名记录中
        this.eventRegistrations = registrations.map(reg => {
          const owner = owners.find(o => o.ownerId === reg.owner_id)
          return {
            ...reg,
            ownerName: owner ? owner.name : '未知用户',
            ownerContact: owner ? owner.contactInfo : ''
          }
        }).filter(reg => reg.event !== null) // 过滤掉无效记录
      } catch (err) {
        this.error = err.message
      }
    }
  },
  created() {
    this.fetchEvents()
    this.fetchMyRegistrations()
  }
}
</script>

<style scoped>
.event-registration-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.event-stats {
  display: flex;
  gap: 20px;
}

.stat-card {
  background: white;
  padding: 15px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.events-filter {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.filter-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-btn.active {
  background: var(--primary-color);
  color: white;
}

.events-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.event-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.event-card:hover {
  transform: translateY(-5px);
}

.event-image {
  position: relative;
  height: 200px;
}

.event-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.event-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  color: white;
  font-size: 0.8rem;
}

.event-status.upcoming {
  background-color: #ff9800;
}

.event-status.active {
  background-color: #4caf50;
}

.event-status.closed {
  background-color: #9e9e9e;
}

.event-status.completed {
  background-color: #f44336;
}

.event-content {
  padding: 20px;
}

.event-desc {
  color: var(--gray);
  margin: 10px 0;
}

.event-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin: 15px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--gray);
  font-size: 0.9rem;
}

.detail-item .icon {
  font-size: 1.1rem;
}

.event-actions {
  margin-top: 15px;
}

.register-btn, .cancel-btn {
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.register-btn {
  background-color: var(--primary-color);
  color: white;
}

.cancel-btn {
  background-color: #f44336;
  color: white;
}

.register-btn:disabled {
  background-color: var(--gray);
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .event-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .event-stats {
    width: 100%;
    justify-content: space-between;
  }

  .events-grid {
    grid-template-columns: 1fr;
  }
}

.event-detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: var(--gray);
}

.modal-body {
  padding: 20px;
}

.event-detail-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 20px;
}

.event-description {
  color: var(--text-color);
  line-height: 1.6;
  margin-bottom: 20px;
}

.event-time-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.label {
  color: var(--gray);
  margin-right: 10px;
}

.registrations-list h3 {
  margin-bottom: 15px;
  color: var(--text-color);
}

.registrations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.registration-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  background: var(--primary-color);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.registration-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  color: var(--text-color);
}

.register-time {
  font-size: 0.8rem;
  color: var(--gray);
}

@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    margin: 10px;
  }

  .registrations-grid {
    grid-template-columns: 1fr;
  }
}
</style> 